package com.atguigui.gulimall.cart.controller;

import com.atguigu.common.utils.R;
import com.atguigui.gulimall.cart.service.CartService;
import com.atguigui.gulimall.cart.vo.CartItemVo;
import com.atguigui.gulimall.cart.vo.CartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.concurrent.ExecutionException;

@Controller
public class CartController {
    @Autowired
    private CartService cartService;

    @GetMapping("/getCheckedCart")
    @ResponseBody
    public R getCheckedCart(){
        List<CartItemVo> list = cartService.getCheckedCart();
        return R.ok().setData(list);
    }

    @GetMapping("/cart.html")
    public String cart(Model model) throws ExecutionException, InterruptedException {
        CartVo cartVo = cartService.cart();
        model.addAttribute("cart",cartVo);
        return "cartList";
    }

    @GetMapping("/success.html")
    public String success(){
        return "success";
    }

    @GetMapping("/addCartItem")
    public String addCartItem(Long skuId, Integer num, RedirectAttributes redirectAttributes) throws ExecutionException, InterruptedException {
        CartItemVo cartItemVo = null;
        cartItemVo = cartService.addCartItem(skuId,num);
        redirectAttributes.addAttribute("skuId",skuId);
        redirectAttributes.addAttribute("num",num);
        return "redirect:http://cart.gulimall.com/success";
    }

    @GetMapping("/success")
    public String SkipTosuccess(String skuId,Integer num,Model model){
        CartItemVo cartItemVo = cartService.getCartItemVoBySkuId(skuId);
        cartItemVo.setAmount(num);
        model.addAttribute("cartItem",cartItemVo);
        return "success";
    }

    @GetMapping("/checkItem")
    public String checkItem(String skuId,Integer checked,Model model) throws ExecutionException, InterruptedException {
        cartService.checkItem(skuId,checked);
        return "redirect:http://cart.gulimall.com/cart.html";
    }

    @GetMapping("/countItem")
    public String countItem(String skuId,Integer num){
        cartService.countItem(skuId,num);
        return "redirect:http://cart.gulimall.com/cart.html";
    }

    @GetMapping("/deleteItem")
    public String deleteItem(String skuId){
        cartService.deleteItem(skuId);
        return "redirect:http://cart.gulimall.com/cart.html";
    }

}
